PepSim.define('PepSim.Pep', {

	defaultDna : {
		speed : 300, 
		energy : 200, 
		cloneEnergy : 100, 
		moveEnergy : 200,
	},
	
	init: function (world, left, top, dna, generation) {
		world.entities.append(this);
		this.world = world;
		this.worldWidth = world.width;
		this.worldHeight = world.height;
		this.generation = generation || 1;
		this.dna = dna || this.defaultDna;
		
		this.speed = this.dna.speed / 100;
		this.initialEnergy = this.dna.energy;
		this.energy = this.dna.energy;
		this.cloneEnergy = this.dna.cloneEnergy;
		this.moveEnergy = (this.dna.moveEnergy / 50) + 1;
		
		this.left = left;
		this.top = top;
		
		this.world.put(this.left, this.top, this);
				
		this.type = 'pep';
	},
	
	tryClone : function () {
		var pep;
		if (this.energy >= this.initialEnergy + this.cloneEnergy) {
			var newLeft = this.left + 1, 
				newTop = this.top;
				
			if (
				newTop < this.worldHeight &&
				newTop >= 0 &&
				newLeft < this.worldWidth &&
				newLeft >= 0)
			{	
				if(!this.world.get(newLeft, newTop)) {
					pep = new PepSim.Pep(this.world, newLeft, newTop, PepSim.mutateDna(this.dna), this.generation + 1);
					this.world.entities.append(pep);
				}
			}
		}
	},

	toString : function () {
		return this.type + '. ' + 
			'Energy: ' + Math.floor(this.energy) + ', ' + 
			'speed: ' + this.speed + ', ' + 
			'cloneEnergy: ' + this.cloneEnergy + ', ' + 
			'moveEnergy: ' + this.moveEnergy;
	},
	
	kill : function () {
		this.phantom = true;
		this.world.clear(this.left, this.top);
	},
	
	move: function () {
		var hDirection = PepSim.rand(3) - 1;
		var vDirection = PepSim.rand(3) - 1;
		var newTop = this.top + vDirection;
		var newLeft = this.left + hDirection;
		var newItem;
		
		if (
			newTop < this.worldHeight &&
			newTop >= 0 &&
			newLeft < this.worldWidth &&
			newLeft >= 0)
		{
			newItem = this.world.get(newLeft, newTop);
			if (!newItem) {
				this.left = newLeft;
				this.top = newTop;
			} else if (newItem.type === 'food') {
				this.energy = this.energy + newItem.energy;
				newItem.energy = 0;
				newItem.phantom = true;
				this.left = newLeft;
				this.top = newTop;
			}
		}
		this.energy = this.energy - this.moveEnergy;
		
	},
	
	// This function handle the entire movement of a pep during its turn
	play: function () {
		if (this.energy > 200) {
			this.energy = 200;
		}
		var i;
		for (i = 0; i < this.speed ; i = i + 1) {
			this.world.clear(this.left, this.top);
			this.move();
			this.world.put(this.left, this.top, this);
		}
		
		this.tryClone();
		
		if (this.energy < 0) {
			this.kill();
		}
	}

});